package com.campos.activity;

import android.annotation.SuppressLint;
import android.media.Image;
import android.os.Bundle;
import android.os.Environment;
import android.util.Size;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraControl;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.view.PreviewView;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.campos.collection.GPSServiceWrapper;
import com.campos.common.ContextData;
import com.campos.common.ImageData;
import com.google.common.util.concurrent.ListenableFuture;

import java.io.File;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;

public class CameraActivity extends AppCompatActivity {
    private PreviewView previewView;
    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private TextView textView;
    private Button takePicButton;
    private Camera camera;
    private CameraControl cameraControl;
    private CameraActivity self;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        previewView = findViewById(R.id.previewView);
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        textView = findViewById(R.id.orientation);
        takePicButton = findViewById(R.id.takePicture);
        self = this;
        cameraProviderFuture.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                    //bindPreview(cameraProvider);
                    bindImageAnalysis(cameraProvider);
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, ContextCompat.getMainExecutor(this));

        CameraActivity that = this;
        Button zoomin = findViewById(R.id.btnZoomIn);
        zoomin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                that.zoomIn();
            }
        });
        Button zoomout = findViewById(R.id.btnZoomOut);
        zoomout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                that.zoomOut();
            }
        });
        Button closebtn = findViewById(R.id.btnClose);
        closebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                that.setResult(0);
                that.finish();
            }
        });
    }

    void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
        Preview preview = new Preview.Builder()
                .build();

        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                .build();

        preview.setSurfaceProvider(previewView.getSurfaceProvider());

        Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector, preview);
    }

    private void bindImageAnalysis(@NonNull ProcessCameraProvider cameraProvider) {
        Executor executor = ContextCompat.getMainExecutor(this);
        ImageAnalysis imageAnalysis =
                new ImageAnalysis.Builder().setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).build();
        imageAnalysis.setAnalyzer(executor, new ImageAnalysis.Analyzer() {
            @Override
            public void analyze(@NonNull ImageProxy image) {
                image.close();
            }
        });
        OrientationEventListener orientationEventListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int orientation) {
                float h = ContextData.instance.currentHeading;
                float p = ContextData.instance.currentPitch;
                float r = ContextData.instance.currentRoll;
                textView.setText("H：" + h + "\nP：" + p + "\nR：" + r);
            }
        };
        orientationEventListener.enable();
        Preview preview = new Preview.Builder().build();
        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
        preview.setSurfaceProvider(previewView.getSurfaceProvider());

        ImageCapture imageCapture =
                new ImageCapture.Builder().build();
        this.camera = cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector,imageCapture,
                imageAnalysis, preview);
        this.cameraControl = this.camera.getCameraControl();

        takePicButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                File file = new File(Environment.getExternalStorageDirectory(),
//                        System.currentTimeMillis() + ".jpeg");
//                ImageCapture.OutputFileOptions outputFileOptions =
//                        new ImageCapture.OutputFileOptions.Builder(file).build();
                imageCapture.takePicture(executor,
                        new ImageCapture.OnImageCapturedCallback() {
                            @Override
                            public void onCaptureSuccess(ImageProxy image) {
                                // insert your code here.
                                @SuppressLint("UnsafeOptInUsageError") Image img = image.getImage();
                                ImageData imd = new ImageData(img);
                                img.close();
                                image.close();
                                Date date = new Date();
                                imd.date = date;
                                imd.pos = GPSServiceWrapper.getInstance().getCurrentGPS();
                                ContextData.instance.imageTimeList.add(date);
                                ContextData.instance.imageList.add(imd);
                                Toast.makeText(self,"已拍照", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onError(ImageCaptureException exception){
                                // insert your code here.
                                exception.printStackTrace();
                            }
                        }
                );
            }
        });
    }
    private float zoomRatio = 1.0f;
    private void zoomIn(){
        zoomRatio = zoomRatio +0.5f;
        this.cameraControl.setZoomRatio(zoomRatio);
    }
    private void zoomOut(){
        zoomRatio = zoomRatio -0.5f;
        this.cameraControl.setZoomRatio(zoomRatio);
    }
}
